package com.jsmile.cloud.promotioncenter.web.mq.order;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.jsmile.cloud.tradecenter.api.enums.OrderStatusEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单变化策略
 */
@Service
@Slf4j
public class OrderStatusStrategyMap implements ApplicationContextAware {

    private final Map<OrderStatusEnum, IOrder> syncHandlerMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IOrder> beansOfTypeMap = applicationContext.getBeansOfType(IOrder.class);
        if (beansOfTypeMap != null) {
            beansOfTypeMap.forEach((key, strategy) -> syncHandlerMap.putIfAbsent(strategy.orderStatus(), strategy));
        }
    }

    public IOrder findStrategy(OrderStatusEnum orderStatus) {
        return syncHandlerMap.get(orderStatus);
    }

    public IOrder findStrategy(int orderStatus) {
        return syncHandlerMap.get(OrderStatusEnum.nameOf(orderStatus));
    }

    public Optional<IOrder> findStrategyOptional(OrderStatusEnum orderStatus) {
        return Optional.ofNullable(syncHandlerMap.get(orderStatus));
    }
}
